import React, { useState } from 'react'
import axios from 'axios'
import PubSub from 'pubsub-js'

export default function Header() {
  //用useState做受控表单方便拿到输入框内容
  const [search, setSearch] = useState('')

  //获取输入框内容
  const changeSearchHandle = (e) => {
    setSearch(e.target.value);
  }

  //点击搜索的事件
  const searchHandle = async () => {
    //点击搜索但是请求还没有响应的时候发布订阅重新渲染让搜索中显示在页面
    PubSub.publish("github" , {isInit: false, isSearch: true, data: []})

    //发送请求
    const result = await axios.get("https://api.github.com/search/users?q=" + search);

    //请求完成发布订阅
    PubSub.publish("github", {isInit: false, isSearch: false, data: result.data.items})

  }

  return (
    <div>
      <section className="jumbotron">
        <h3 className="jumbotron-heading">Search Github Users</h3>
        <div>
          <input type="text" value={search} onChange={changeSearchHandle} placeholder="enter the name you search" />
          &nbsp;
          <button onClick={searchHandle}>Search</button>
        </div>
      </section>
    </div>
  )
}
